package com.tuanbiao.presenter;

import androidx.annotation.NonNull;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.abiao.lib_utils.IntentUtils;
import com.abiao.lib_utils.NetworkUtils;
import com.abiao.lib_utils.SPUtils;
import com.hzjq.data.callback.ProgressHttpCallback;
import com.hzjq.data.entity.BlastLonLat;
import com.hzjq.data.hzjq.entity.AppDataEntity;
import com.hzjq.lib.BlastKool;
import com.hzjq.lib.checker.CheckError;
import com.hzjq.lib.location.LocationLoader;
import com.hzjq.lib.wiget.RepeatDialog;
import com.tuanbiao.App;
import com.tuanbiao.AppConfig;
import com.tuanbiao.base.mvp.BasePresenter;
import com.tuanbiao.constants.SPConstants;
import com.tuanbiao.controllers.MainController;
import com.tuanbiao.data.callback.OnBaseResultCallback;
import com.tuanbiao.transformers.SchedulerTransformer;
import com.tuanbiao.utils.SettingUtils;

import java.io.File;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import timber.log.Timber;

/**
 * @author abiao
 * @since 2022/3/28 9:46
 */
public class MainPresenter extends BasePresenter<MainController.Model, MainController.View> implements MainController.Presenter, LocationLoader.OnLocationChangeListener, NetworkUtils.OnNetworkStatusChangedListener {
    private long startTime = SPUtils.getInstance().getLong(SPConstants.SP_KEY_BATTERY_TIME, 0);
    public MainPresenter(MainController.Model model, MainController.View rootView) {
        super(model, rootView);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void loadApp() {
//        BlastKool.Companion.loader().setBlastLogMaxCount(3);
        mModel.loadApp(false, new OnBaseResultCallback<AppDataEntity>() {
            @Override
            public void onSuccess(AppDataEntity entity) {
                if (SettingUtils.compareVersion(entity.getVersioncode(), AppConfig.getVersionName())) {
                    mRootView.showUpdateDialog(entity);
                } else {
                    mRootView.showMessage("已经是最新版本了");
                }
            }
        });
//        if (LocationUtils.isLocationEnabled()) {
//            mRootView.showLocationDisableDialog();
//        }

        if (AppConfig.startBatteryInterval()) {
            mRootView.showBatterInterval(true,millis2FitTimeSpan(SPUtils.getInstance().getLong(SPConstants.SP_KEY_BATTERY_TIME, 0)));
            Observable.interval(1, TimeUnit.SECONDS)
                    .compose(new SchedulerTransformer())
                    .subscribe(o -> {
                        Timber.i("timer:" + startTime);
                        startTime++;
                        mRootView.showBatterInterval(true,millis2FitTimeSpan(startTime));
                        SPUtils.getInstance().put(SPConstants.SP_KEY_BATTERY_TIME, startTime);
                    });
        }else {
            mRootView.showBatterInterval(false,millis2FitTimeSpan(SPUtils.getInstance().getLong(SPConstants.SP_KEY_BATTERY_TIME, 0)));
        }
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void registerNet() {
        NetworkUtils.registerNetworkStatusChangedListener(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void setForceBlastCheck(){
        mModel.changeForceAuth(true);
        mModel.changeForceBlast(true);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    private void unregisterNet() {
        NetworkUtils.unregisterNetworkStatusChangedListener(this);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void getDeviceInfo() {
        mModel.getDeviceInfo(entity -> mRootView.showSubTitle(entity.getNum()));
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void startLocate() {
        mModel.refreshAuth();
        BlastKool.Companion.loader()
                .location()
                .addLocationChangeListener(this)
                .start();
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_RESUME)
    private void showRepeatCapDialog(){
        BlastKool.Companion.loader()
                .setOnPlanCheckRepeatResultCallback(repeatResult ->
                        RepeatDialog.Companion.show(repeatResult)
                );
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_PAUSE)
    private void stopLocate() {
        BlastKool.Companion.loader()
                .location().removeLocationChangeListener(this);
    }
    @OnLifecycleEvent(Lifecycle.Event.ON_CREATE)
    private void checkUnUploadCount() {
        mModel.checkUnUploadCount(new OnBaseResultCallback<CheckError>() {
            @Override
            public void onSuccess(CheckError checkError) {
                Timber.i("checkUnUploadCount#"+checkError.getErrorMsg());
                if (checkError.getErrorCode() != CheckError.CHECK_SUCCESS) {
                    mRootView.showUploadDialog();
                }
            }
        });
    }
//
//    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
//    private void destroyLocal() {
//        Timber.i("destroyLocal");
//        BlastKool.Companion.loader()
//                .location().onDestroy();
//    }

    @Override
    public void startPlanManage() {
        if (null != mModel.getCurrentProject()) {
            mRootView.startPlanManage();
        } else {
            mRootView.showMessage("请先添加且绑定一个项目");
        }
    }

    @Override
    public void startBlast() {
        mRootView.showCheckDialog();
        mModel.checkNetted(error -> {
            mRootView.hideCheckDialog();
            if (error.getErrorCode() == CheckError.CHECK_SUCCESS) {
                mRootView.startBlast();
            } else {
                mRootView.showMessage(error.getErrorMsg());
            }
        });
    }

    @Override
    public void startAuth() {
        if (null != mModel.getCurrentProject()) {
            if (mModel.getSettingParams().isStandAloneModel()) {
                mRootView.showMessage("单机模式无需授权！");
            } else {
                mRootView.startAuth();
            }
        } else {
            mRootView.showMessage("请先添加且绑定一个项目");
        }
    }

    @Override
    public void startSingleCheck() {
        if (null != mModel.getCurrentProject()) {
            mRootView.startSingleCheck();
        } else {
            mRootView.showMessage("请先添加且绑定一个项目");
        }
    }

    @Override
    public void startLocation() {
        if (null != mModel.getCurrentProject()) {
            mRootView.startLocation();
        } else {
            mRootView.showMessage("请先添加一个项目");
        }
    }

    @Override
    public void downloadApk(AppDataEntity entity) {
        mModel.downLoadApk(entity, new ProgressHttpCallback<File>() {
            @Override
            public void onProgressChanged(int i, int i1) {
                Timber.i("downloadApk#onProgressChanged#i:" + i + ",i1:" + i1);
            }

            @Override
            public void onSuccess(File file) {
                Timber.i("downloadApk#onSuccess:" + file);
                mRootView.startInstall(IntentUtils.getInstallAppIntent(file));
            }

            @Override
            public void onFailed(@NonNull String s) {
                Timber.i("downloadApk#s:" + s);
                mRootView.showMessage(s);
            }
        });
    }

    @Override
    public void onLocationChanged(@NonNull BlastLonLat blastLonLat) {
        //Timber.i("onLocationChanged:" + blastLonLat);
        App.getInstance().setCurrentLocation(blastLonLat);
        mRootView.showLonLat(blastLonLat);
    }

    @Override
    public void onDisconnected() {
        Timber.i("onDisconnected");
        BlastKool.Companion.loader()
                .location().removeLocationChangeListener(MainPresenter.this);
    }

    @Override
    public void onConnected(NetworkUtils.NetworkType networkType) {
        Timber.i("onConnected");
        BlastKool.Companion.loader()
                .location()
                .addLocationChangeListener(MainPresenter.this)
                .start();
    }

    @Override
        public void clearBatteryInterval() {
        startTime = 0;
        SPUtils.getInstance().remove(SPConstants.SP_KEY_BATTERY_TIME);
    }

    private String millis2FitTimeSpan(long time) {
        if (time == 0) return 0 + "秒";
        StringBuilder sb = new StringBuilder();
        if (time < 0) {
            sb.append("-");
            time = -time;
        }
        if (time < 60) {
            return time + "秒";
        } else if (time < 3600) {
            long mode = time / 60;
            return mode + "分:" + time % 60 + "秒";
        } else if (time < 86400) {
            long hour = time / 3600;
            long min = time % 3600 / 60;
            long sec = time % 3600 % 60;
            return hour + "时:" + min + "分:" + sec + "秒";
        } else if (time > 86400) {
            long day = time / 86400;
            long hour = time % 86400 / 3600;
            long min = time % 86400 % 3600 / 60;
            long sec = time % 86400 % 3600 % 60;
            return day + "天:" + hour + "时:" + min + "分:" + sec + "秒";
        } else {
            return "0秒";
        }

    }
}
